var ws = require("nodejs-websocket")
var port=9000;
var user=0;

// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
    console.log("New connection",conn);
    user++;
    conn.nickname="user"+user;
    broadcast(conn.nickname+" comes in");
    conn.on("text", function (str) {
        console.log("Received "+str)
        //conn.sendText(str.toUpperCase()+"!!!")
        broadcast(str);
    })
    conn.on("close", function (code, reason) {
        console.log("Connection closed");
        broadcast(conn.nickname+" left ");
    })
    conn.on("error", function (err) {
        console.log("handdle error");
        console.log(err);
    })
}).listen(port);
console.log("websocket server listening on port "+port);
function broadcast(str){
    server.connections.forEach(function(connection){
        connection.sendText(str);
    })
}
